package com.zlm.hp.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.TelephonyManager;

import com.zlm.hp.manager.AudioPlayerManager;

/**
 * 电话监听器类
 */
public class PhoneStateReceiver {

    private BroadcastReceiver receiver;
    private final IntentFilter filter;

    public PhoneStateReceiver() {
        filter = new IntentFilter();
        filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
    }

    /**
     * 注册广播
     * @param context
     */
    public void registerReceiver(Context context) {
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
                if(TelephonyManager.EXTRA_STATE_IDLE.equals(state)) {// 挂机状态
                    AudioPlayerManager.newInstance(context).playOrPause();
                } else {
//                    case TelephonyManager.EXTRA_STATE_OFFHOOK:	//通话状态
//                    case TelephonyManager.EXTRA_STATE_RINGING:	//响铃状态
                    AudioPlayerManager.newInstance(context).pause();
                }
            }
        };
        context.registerReceiver(receiver, filter);
    }

    /**
     * 取消注册广播
     */
    public void unregisterReceiver(Context context) {
        if (receiver != null) {
            context.unregisterReceiver(receiver);
        }
    }

    public IntentFilter getFilter() {
        return filter;
    }
}
